package com.dmc.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dmc.conf.Constant;
import com.dmc.dict.*;
import com.dmc.entity.*;
import com.dmc.mapper.*;
import com.dmc.model.*;
import com.dmc.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dmc.util.DecimalUtil;
import com.dmc.util.SessionUtil;
import com.dmc.util.id.IdUtil;
import com.dmc.util.util.GetOrderIdByTime;
import com.dmc.util.util.OrderCodeUtil;
import com.dmc.util.util.StringUtil;
import com.dmc.vo.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @
 * @since 2020-09-06
 */
@Service
@Transactional
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    private Logger logger= LoggerFactory.getLogger(OrdersServiceImpl.class);
    @Resource
    private OrderDetailService orderDetailService;

    @Resource
    private UserAccountService userAccountService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private SysConfMapper sysConfMapper;

    @Autowired
    private LogisticsMapper logisticsMapper;

    @Autowired
    private OrdersLogisticsMapper ordersLogisticsMapper;

    @Autowired
    private IntegralTransactionMapper integralTransactionMapper;

    @Autowired
    private UserMapper userMapper;

    @Resource
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private TGoodsSkuMapper tGoodsSkuMapper;

    @Autowired
    private TGoodsSpuMapper tGoodsSpuMapper;

    @Autowired
    private PaymentMapper paymentMapper;

    @Autowired
    private BenefitTransactionMapper benefitTransactionMapper;

    @Autowired
    private PlatformBankCardMapper platformBankCardMapper;

    @Autowired
    private TUserAccountMapper tUserAccountMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;


    @Autowired
    private UserSpuPayNumMapper userSpuPayNumMapper;


    /**
     * 创建订单
     * @param ordersVo
     * @return
     */
    @Override
    public List<String> createOrder(OrdersVo ordersVo) {
        List<TGoodsDetailVo> ordersSkuList= new ArrayList<>();
        List<TGoodsDetailVo> ordersSubSkuList= new ArrayList<>();
        Map<String,Object> param = new HashMap<>();
        Integer createOrderType = ordersVo.getCreateOrderType();
        boolean isCart = createOrderType!=null && createOrderType == 1;
        Long userId=SessionUtil.getCurrUid();
        param.put("user_id",userId);
        //重新计算金额进行金额校验\
        boolean isIntegralOrder = false;
        Long currUid = SessionUtil.getCurrUid();
        for (TGoodsDetailVo goodsDetailVo:ordersVo.getSkuList()){
            Long goodsSpuId = goodsDetailVo.getGoodsSpuId();
            BigDecimal skuNum = goodsDetailVo.getSkuNum();
            Integer quantity = goodsDetailVo.getQuantity();
            Boolean payLimitCheck = goodsService.checkPayNumLimit(goodsSpuId,quantity == null?1:quantity);
            Assert.isTrue(payLimitCheck,"此商品你的购买数量已经超限制");
            //添加购买数量
            addPaySpuNum( currUid,  goodsSpuId,  skuNum == null?1:quantity == null?1:quantity);
            logger.info("goodsDetailVo.getSpecial():"+goodsDetailVo.getSpecial());
            BigDecimal integral = goodsDetailVo.getIntegral();
            BigDecimal skuCurrPrice = goodsDetailVo.getSkuCurrPrice();
            Integer integralStatus = goodsDetailVo.getIntegralStatus();
            if(!isIntegralOrder){
                isIntegralOrder = integralStatus != null && integralStatus == 1;
            }
            if(goodsDetailVo.getSpecial().equals(1)){
                //特殊商品重新生成订单
                ordersSubSkuList.add(goodsDetailVo);
            }else{
                ordersSkuList.add(goodsDetailVo);
            }

            if(isCart){
                //删除购物车当前SKU数据
                param.put("sku_id",goodsDetailVo.getSkuId());
                shoppingCartMapper.deleteByMap(param);
            }
        }


        ordersVo.setIntegralOrder(isIntegralOrder?1:0);
        List<String> ordersNoList=new ArrayList<>();
        //生成父订单
        String fatherOrdersNo=createOrders(ordersVo,ordersSkuList,1,"");
        ordersNoList.add(fatherOrdersNo);
        if(!CollectionUtils.isEmpty(ordersSubSkuList)){
            //重新生成订单
            String ordersNo=createOrders(ordersVo,ordersSubSkuList,0,fatherOrdersNo);
//            ordersNoList.add(ordersNo);
        }
        //如果是购物车下单则删除购物车数据

        return ordersNoList;
    }

    @Override
    public void reviewOfflineOrder(OrdersVo ordersVo) {
        Integer ordersId = ordersVo.getOrdersId();
        Assert.notNull(ordersId,"参数错误,请传输订单号");
        Orders orders = ordersMapper.selectById(ordersId);
        Assert.notNull(orders,"参数错误,此订单");
        Integer payWay = orders.getPayWay();
        String ordersNo = orders.getOrdersNo();
        //线下支付才需要审核
        boolean isOffline = payWay!=null && payWay == 6 && payWay == 7 && payWay == 8 && payWay == 9;
        Assert.isTrue(isOffline,"线上支付,无需审核");
        long checkoutId = IdUtil.generateId();
        Payment payment = new Payment();
        payment.setPayNo(OrderCodeUtil.getPayCode(orders.getUserId()));
        payment.setStartTime(new Date());
        payment.setPaymentResult("线下支付");
        payment.setPaymentStatus(PaymentStatusDict.PAYMENT_STATUS_SUCCESS.getCn());
        payment.setUserId(orders.getUserId());
        payment.setPayType(PaymentTypeDict.PAYMENT_TYPE_PAY.getCn());
        payment.setOrderId(ordersNo);
        payment.setCheckoutId(IdUtil.generateId());
        payment.setAmount(orders.getFinalAmount().multiply(new BigDecimal("100")));
        payment.setOrderType(OrderTypeDict.ORDER_TYPE_GOODS.getCn());
        payment.setOfflineStatus(OrderLineStatusDict.ORDER_LINE_STATUS_OFF.getCn());
        payment.setId(IdUtil.generateId());
        payment.setCreateTime(new Date());
        paymentMapper.insert(payment);
        //前置处理
        payOrderProcess(ordersNo,checkoutId);
        //后置处理
        payOrderProcess(PaymentTypeDict.PAYMENT_TYPE_PAY.getCn(), ordersNo, OrderTypeDict.ORDER_TYPE_GOODS.getCn());
    }

    /**
     * 生成订单
     * @param ordersVo 订单信息
     * @param skuList 商品信息
     * @param fatherOrders 是否为父订单（0表示否、1表示是）
     * @param fatherOrdersNo 父订单号
     * @return
     */
    private String createOrders(OrdersVo ordersVo,List<TGoodsDetailVo> skuList,Integer fatherOrders,String fatherOrdersNo){
        Orders orders = new Orders();
        Integer payWay = ordersVo.getPayWay();
        Assert.isTrue(payWay!=null,"支付方式不能为空");
        //判断是否是会员商品订单
        int vipOrder = 0;
        if(!CollectionUtils.isEmpty(skuList)){
            for (TGoodsDetailVo tGoodsDetailVo : skuList) {
                Long goodsSpuId = tGoodsDetailVo.getGoodsSpuId();
                TGoodsSpu tGoodsSpu = tGoodsSpuMapper.selectById(goodsSpuId);
                if(tGoodsSpu!=null && tGoodsSpu.getVip()==1){
                    vipOrder = 1;
                    break;
                }
            }
        }
        //1、微信支付 2、积分支付 3 扫码支付 6线下现金支付 7线下转账支付 4微信混合支付 5扫码混合支付 8线下现金支付 9线下转账支付
        if(vipOrder == 1){
            if(!(payWay == 1 || payWay == 3 || payWay == 6 || payWay == 7 || payWay == 10)){
                throw new IllegalArgumentException("会员商品不支持含积分否买");
            }
        }
        Integer integralOrder = ordersVo.getIntegralOrder();
        if(integralOrder!=null && integralOrder==1 && ordersVo.getUseIntegral() == null){
            ordersVo.setUseIntegral(ordersVo.getIntergralAmount());
        }

        Long userId=SessionUtil.getCurrUid();
        String ordersNo = OrderCodeUtil.getOrderCode(userId);
        logger.debug("创建订单,订单号{0},用户id:"+ordersNo+"{1},"+userId+"{2},"+ordersVo.getUseIntegral()+"{3},"+ordersVo.getTotalAmount()+"{4},"+ordersVo.getFinalAmount());
        String configValue = getConfigValue(Constant.CONFIG_KEY_GOOS_DISCOUNT_RATE);

        orders.setOrdersNo(ordersNo);//订单号
        orders.setUserId(userId);//会员ID
        orders.setReceiverDistrict(ordersVo.getReceiverDistrict());//区县
        orders.setReceiverName(ordersVo.getReceiverName());//收货人
        orders.setReceiverAddress(ordersVo.getReceiverAddress());//详细地址
        orders.setReceiverMobile(ordersVo.getReceiverMobile());//手机号
        orders.setPayWay(ordersVo.getPayWay());//暂时定为1，支付方式设计完再修改
        logger.info("createOrders originalAmount:{},finalAmount:{}",ordersVo.getOriginalAmount(),ordersVo.getFinalAmount());
        orders.setOriginalAmount(ordersVo.getOriginalAmount());
        orders.setFinalAmount(ordersVo.getFinalAmount());
        orders.setIntegralOrder(ordersVo.getIntegralOrder());
        //1、微信支付 2、积分支付 3 扫码支付 4微信混合支付 5扫码混合支付
        if(ordersVo.getUseIntegral()!=null){
            if(ordersVo.getPayWay()==2){
                //使用全部积分
                orders.setUseIntegral(ordersVo.getUseIntegral());
                orders.setTotalAmount(ordersVo.getTotalAmount());
                orders.setFinalAmount(null);
            }else{
                //混合支付

                BigDecimal finalAmount = ordersVo.getTotalAmount().
                        subtract(ordersVo.getUseIntegral());
                log.info("createOrders totalAmount:{},useIntegral:{},finalAmount{},finalAmountOld{}",ordersVo.getTotalAmount(),ordersVo.getUseIntegral(),finalAmount,ordersVo.getFinalAmount());
                Assert.isTrue(ordersVo.getFinalAmount().compareTo(finalAmount)==0,"应付金额有误");
                //部分积分部分金额,总金额-积分=应付金额
                orders.setUseIntegral(ordersVo.getUseIntegral());
                orders.setFinalAmount(ordersVo.getFinalAmount());//商品应付金额
                orders.setTotalAmount(ordersVo.getTotalAmount());//商品总金额
            }
        }else{
            orders.setUseIntegral(ordersVo.getUseIntegral());
            orders.setOriginalAmount(ordersVo.getOriginalAmount());
            orders.setFinalAmount(ordersVo.getFinalAmount());
            orders.setTotalAmount(ordersVo.getFinalAmount());//商品总金额
        }
        Date now=new Date();
        orders.setOrdersState(OrderStatusDict.ORDER_STATUS_CREATED.getCn());//订单状态，未处理
        orders.setDeleteFlag(0);
        orders.setLogisticsState(0);
        orders.setTradeState(0);
        if (StringUtils.isNotBlank(fatherOrdersNo)){
            orders.setFatherOrdersNo(fatherOrdersNo);//父订单号
        }
        //保存当时的商品折扣
        orders.setDiscountRate(new BigDecimal(configValue));
        orders.setFatherOrders(fatherOrders);
        orders.setCreateTime(now);
        orders.setUpdateTime(now);
        orders.setVipOrder(vipOrder);
        insertAllColumn(orders);
        //生成订单商品明细
        generateOrderDetail(skuList,orders.getOrdersId(),ordersNo);
        return ordersNo;
    }
    /**
     * 生成订单商品明细
     * @param skuList
     * @param ordersId
     * @param ordersNo
     */
    private void generateOrderDetail(List<TGoodsDetailVo> skuList,Integer ordersId,String ordersNo){
//        List<OrderDetail> orderDetailList=new ArrayList<>();
        for (TGoodsDetailVo goodsSkuVo:skuList){
            List<SpuSpecsTypeVo> specsTypeList = goodsSkuVo.getSpecsTypeList();
            String skuTitleAll = null;
            String skuTypeAll = null;
            if(CollectionUtil.isNotEmpty(specsTypeList)){
                StringBuffer skuTypeBuffer =new StringBuffer();
                StringBuffer skuTitleBuffer =new StringBuffer();
                for (SpuSpecsTypeVo spuSpecsTypeVo : specsTypeList) {
                    String skuType = spuSpecsTypeVo.getSkuType();
                    skuTypeBuffer.append(Constant.SPECS_SEPARATOR);
                    skuTypeBuffer.append(skuType);
                    List<SpuSpecsVo> specsList = spuSpecsTypeVo.getSpecsList();
                    if(CollectionUtil.isNotEmpty(specsList)){
                        for (SpuSpecsVo spuSpecsVo : specsList) {
                            String skuTitle = spuSpecsVo.getSkuTitle();
                            skuTitleBuffer.append(Constant.SPECS_SEPARATOR);
                            skuTitleBuffer.append(skuTitle);
                        }
                    }
                    skuTypeAll = skuTypeBuffer.toString().substring(1,skuTypeBuffer.length());
                }
                skuTitleAll = skuTitleBuffer.toString().substring(1,skuTitleBuffer.length());
            }

            Long goodsSpuId = goodsSkuVo.getGoodsSpuId();
            TGoodsSpu tGoodsSpu = tGoodsSpuMapper.selectById(goodsSpuId);
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setVip(tGoodsSpu.getVip());
            orderDetail.setOrdersId(ordersId);
            orderDetail.setOrdersNo(ordersNo);
            orderDetail.setQuantity(goodsSkuVo.getQuantity());
            orderDetail.setSkuId(goodsSkuVo.getId());
            orderDetail.setGoodsSpuId(goodsSkuVo.getGoodsSpuId());
            orderDetail.setSkuNo(goodsSkuVo.getSkuNo());
            orderDetail.setSkuTitleType(StringUtil.isNotEmpty(goodsSkuVo.getSkuTitleType())?goodsSkuVo.getSkuTitleType():skuTypeAll);
            orderDetail.setSkuTitle(StringUtil.isNotEmpty(goodsSkuVo.getSkuTitle())?goodsSkuVo.getSkuTitle():skuTitleAll);
            orderDetail.setSkuCoversUrl(goodsSkuVo.getSkuCoversUrl());
            orderDetail.setSkuImgUrl(goodsSkuVo.getSkuImgUrl());
            orderDetail.setSkuNum(goodsSkuVo.getSkuNum());
            orderDetail.setSkuSaleNum(goodsSkuVo.getSkuSaleNum());
            orderDetail.setSkuCostPrice(goodsSkuVo.getSkuCostPrice());
            orderDetail.setSkuCurrPrice(goodsSkuVo.getSkuCurrPrice());
            orderDetail.setDes(goodsSkuVo.getDes());
            orderDetail.setSkuStatus(goodsSkuVo.getStatus());
            orderDetail.setSpuNo(goodsSkuVo.getSpuNo());
            orderDetail.setGoodsName(goodsSkuVo.getGoodsName());
            orderDetail.setCategoryId(goodsSkuVo.getCategoryId());
            orderDetail.setSpecial(goodsSkuVo.getSpecial());
            orderDetail.setSkuDetail(goodsSkuVo.getSkuDetail());
            orderDetail.setSkuDetailImgUrl(goodsSkuVo.getSkuDetailImgUrl());
            Date now=new Date();
            orderDetail.setCreateTime(now);
            orderDetail.setUpdateTime(now);
            orderDetailService.insertAllColumn(orderDetail);
        }

    }

    /**
     * 用户订单信息
     * @param
     * @return
     */
    @Override
    public List<OrdersVo> getOrderByUserId(Long currUid,Long ordersState,String keyWord) {
        List<OrdersVo> resultOrderList=new ArrayList<>();
        if(StringUtils.isNotBlank(keyWord)){
            keyWord = "%"+keyWord.trim()+"%";
        }
        //先拿到用户所有订单
        List<Orders> ordersList=ordersMapper.getOrdersByUser(currUid,ordersState,keyWord);
        for (Orders o:ordersList){
            OrdersVo ordersVo=new OrdersVo();
            BeanUtils.copyProperties(o, ordersVo);
            //然后通过订单号去拿商品明细数据
            List<OrderDetail> orderDetailList=orderDetailMapper.getOrderDetailByOrderId(o.getOrdersId());
            ordersVo.setOrderDetailList(orderDetailList);
            ordersVo.setOrdersName(OrderStatusDict.getDescByCn(o.getOrdersState()));
            resultOrderList.add(ordersVo);
        }
        return resultOrderList;
    }

    /**
     * 获取订单列表
     * @param ordersVo
     * @return
     */
    @Override
    public DataTable<OrdersVo> getOrder(OrdersVo ordersVo){
        Integer start = ordersVo.getStart();
        if(start == null){
            ordersVo.setStart(0);
        }
        Integer length = ordersVo.getLength();
        if(length == null){
            ordersVo.setLength(10);
        }
        //商品名称
        String goodsName = ordersVo.getGoodsName();
        if(StringUtils.isNotBlank(goodsName)){
            goodsName = "%"+goodsName.trim()+"%";
            ordersVo.setGoodsName(goodsName);
        }
        PageHelper.startPage(ordersVo.getStart(), ordersVo.getLength());
        //获取订单
        List<OrdersVo> ordersMapperOrdersList=ordersMapper.getOrdersList(ordersVo);
//        List<Orders> ordersList =  ordersMapper.getOrders(ordersVo);
        for (OrdersVo o:ordersMapperOrdersList){
            BigDecimal originalAmount = o.getOriginalAmount();
            BigDecimal finalAmount = o.getFinalAmount();
            BigDecimal preferentialAmount = DecimalUtil.subArrayOriginalValue(originalAmount, finalAmount);
            o.setPreferentialAmount(preferentialAmount.compareTo(BigDecimal.ZERO)<=0?BigDecimal.ZERO:preferentialAmount);
            //然后通过订单号去拿商品明细数据
            List<OrderDetail> orderDetailList=orderDetailMapper.getOrderDetailByOrderId(o.getOrdersId());
            o.setOrderDetailList(orderDetailList);
            //订单物流信息
            Map<String,Object> param=new HashMap<>();
            param.put("orders_no",o.getOrdersNo());
            List<OrdersLogistics> ordersLogisticsList=ordersLogisticsMapper.selectByMap(param);
            o.setOrdersLogisticsList(ordersLogisticsList);
        }
        DataTable<OrdersVo> tables = new DataTable<>();
        tables.setRecordsTotal(((Page) ordersMapperOrdersList).getTotal());
        tables.setRecordsFiltered(tables.getRecordsTotal());
        tables.setDraw(ordersVo.getDraw());
        tables.setData(ordersMapperOrdersList);
        return tables;
    }

    /**
     * 根据订单号查订单明细
     * @param ordersNo
     * @return
     */
    @Override
    public List<OrderDetail> getOrderDetailByOrderNo(String ordersNo){
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("orders_no",ordersNo);
        List<OrderDetail> orderDetailList=orderDetailMapper.selectByMap(paramMap);
        return orderDetailList;
    }

    /**
     * 订单全积分支付,部分积分支付等全部支付完成再减积分
     * @param ordersNo
     * @param userId
     * @param useIntegral
     */
    @Override
    public void useIntegralPay(String ordersNo,Long userId,BigDecimal useIntegral){
        if (StringUtils.isBlank(ordersNo)||useIntegral==null){
            Assert.isTrue(false,"订单号和使用积分不能为空");
        }
        Orders orders=new Orders();
        orders.setOrdersNo(ordersNo);
        Orders data=ordersMapper.selectOne(orders);
        Assert.notNull(data,"找不到该订单号");
        Assert.isTrue(data.getUseIntegral()!=null,"该订单没有积分值");
        Long ordersState = data.getOrdersState();
        User byId = userMapper.getById(userId);
        if(ordersState!=null && OrderStatusDict.ORDER_STATUS_CREATED.getCn() == ordersState){
            BigDecimal finalAmount = data.getFinalAmount();
            Assert.isTrue(finalAmount == null ||finalAmount.compareTo(BigDecimal.ZERO)==0,"此订单为混合支付,无法使用积分支付");
            //拆分子订单不在记积分明细,维护积分记录，在支付完扣除账户积分
            //扣除用户账户本单积分
            TUserAccount userAccount = userAccountService.initUserAccountByUserId(userId);
            Assert.notNull(userAccount,"找不到该用户积分账户");
            //如果有积分值,则还要校验积分值
            useIntegralCommon( userId, data.getOrdersId(),userAccount,useIntegral);
            tUserAccountMapper.updateById(userAccount);
            //并更改订单状态
            data.setOrdersState(OrderStatusDict.ORDER_STATUS_PAIED.getCn());
            Message message=new Message();
            message.setUserId(-1L);
            message.setOrderId((long)data.getOrdersId());
            message.setOrderType(1);
            message.setType(3);
            message.setMessage(byId.getUsername()+"购买了商品订单,订单编号:"+data.getOrdersNo());
            userAccountService.addUserMessage(message);
            Date now=new Date();
            data.setTradeState(1);
            data.setPayTime(now);
            data.setUpdateTime(now);
            ordersMapper.updateById(data);
            //进行库存判断
            String checkResult=payCheckSkuNum(ordersNo);
            Assert.isTrue(checkResult=="",checkResult);
            //添加商品销量
            skuNumIncreaseOrDecrease(ordersNo,1);
        }
    }

    /**
     * 支付时,积分得处理
     * @param userId
     * @param orderId
     * @param userAccount
     */
    private void useIntegralCommon(Long userId,Integer orderId,TUserAccount userAccount,BigDecimal useIntegral){
        //扣除用户账户本单积分
        BigDecimal lastIntegral = userAccount.getIntegral().subtract(useIntegral);
        Assert.isTrue(lastIntegral.compareTo(BigDecimal.ZERO)>=0,"支付失败,积分不足");
        userAccount.setIntegral(lastIntegral);
        IntegralTransaction integralTransaction = new IntegralTransaction();
        integralTransaction.setUserId(userId);
        integralTransaction.setType(IntegralTranTypeDict.NTEGRAL_TRAN_TYPE_GOODS.getCn());
        integralTransaction.setIntegral(useIntegral.negate());
        integralTransaction.setOrderId(Long.parseLong(orderId+""));
        integralTransaction.setDes("购买商品积分");
        integralTransaction.setCreateTime(new Date());
        integralTransaction.setUpdateTime(new Date());
        if(lastIntegral!=null) {
            integralTransaction.setAccountTotalIntegral(lastIntegral);
        }
        userAccountService.addIntegralTransaction(integralTransaction);
    }

    /**
     * 用户申请订单退款
     * @param ordersVo
     * @return
     */
    public Integer orderRefund(OrdersVo ordersVo){
        Assert.isTrue(ordersVo.getOrdersNo()!=null, "订单号不能为空");
        Assert.isTrue(ordersVo.getRefundDes()!=null, "退款原因不能为空");
        Orders orders=new Orders();
        orders.setOrdersNo(ordersVo.getOrdersNo());
        Orders result=ordersMapper.selectOne(orders);
        Assert.notNull(result,"找不到该订单");
        Integer vipOrder = result.getVipOrder();
        Assert.isTrue(vipOrder==null || vipOrder!=1, "会员商品订单无法退货退款");
        Assert.isTrue(result.getTradeState()==1, "该订单未支付不能退款");
        Assert.isTrue(result.getRefundTime()==null, "该订单已经申请了退款");
        Long currUid = com.dmc.util.util.SessionUtil.getCurrUid();
        User byId = userMapper.getById(currUid);
        Message message=new Message();
        message.setUserId(-1L);
        message.setOrderId((long)result.getOrdersId());
        message.setOrderType(1);
        message.setType(3);
        message.setMessage(byId.getUsername()+"申请了商品订单退款,订单编号:"+result.getOrdersNo());
        userAccountService.addUserMessage(message);
        result.setOrdersState(OrderStatusDict.ORDER_STATUS_REFUND.getCn());//申请退款
        result.setRefundAmount(result.getFinalAmount());//退款金额
        result.setRefundIntegral(result.getUseIntegral());
        Date now=new Date();
        result.setRefundDes(ordersVo.getRefundDes());
        if(ordersVo.getRefundImg()!=null) {
            result.setRefundImg(ordersVo.getRefundImg());
        }
        result.setRefundTime(now);
        result.setUpdateTime(now);
        return ordersMapper.updateById(result);
    }

    private void refundPrice(Orders result){
        BigDecimal finalAmount = result.getFinalAmount();

        BigDecimal useIntegral = result.getUseIntegral();
        if(useIntegral!=null && useIntegral.compareTo(BigDecimal.ZERO)>=0){
            refundUseIntegral(result.getOrdersNo(),result.getUserId(),useIntegral);
        }
        refundBackOrderExePre(result.getOrdersNo());
        PaymentVo payment=new PaymentVo();
        //金额(元)转换为分
        BigDecimal refundAmount = null;
        if (result.getRefundAmount()!=null){
            refundAmount=DecimalUtil.mul(result.getRefundAmount().toString(),"100");
        }
        logger.info("退款金额(元)转换为分refundAmount:"+refundAmount);
        RestRespResult<String> rs=null;
        if(finalAmount!=null && finalAmount.compareTo(BigDecimal.ZERO)>=0 && result.getPayWay()==10){
            refundUseBenefitl(result.getOrdersNo(),result.getUserId(),finalAmount);
        }
        if(result.getPayWay()==1 && refundAmount!=null){
            //微信
            payment.setPayType(PayTypeDict.PAY_TYPE_WECHAT.getCn());
            payment.setPayModel(PayModeDict.PAY_MODE_MINI_APP.getCn());
            payment.setCheckoutId(result.getPaymentId());
            payment.setOrderId(result.getOrdersNo());
            payment.setAmount(refundAmount.intValue()+"");
            PayService payService = AbstractPayServiceImpl.getPayService(payment.getPayType(), payment.getPayModel());
            rs=payService.refund(payment);
            if(rs!=null&&rs.getCode()==RestResp.ERROR){
                Assert.isTrue(false,"退款失败");
            }
        }
        if(result.getPayWay()==3 && refundAmount!=null){
            //支付宝
            payment.setPayType(PayTypeDict.PAY_TYPE_ALIPAY.getCn());
            payment.setPayModel(PayModeDict.PAY_MODE_MINI_NATIVE.getCn());
            payment.setCheckoutId(result.getPaymentId());
            payment.setOrderId(result.getOrdersNo());
            payment.setAmount(refundAmount.intValue()+"");
            PayService payService = AbstractPayServiceImpl.getPayService(payment.getPayType(), payment.getPayModel());
            rs=payService.refund(payment);
            if(rs!=null&&rs.getCode()==RestResp.ERROR){
                Assert.isTrue(false,"退款失败");
            }
        }
        if(result.getPayWay()==4){
            if( refundAmount!=null){
                //退微信部分
                payment.setPayType(PayTypeDict.PAY_TYPE_WECHAT.getCn());
                payment.setPayModel(PayModeDict.PAY_MODE_MINI_APP.getCn());
                payment.setCheckoutId(result.getPaymentId());
                payment.setOrderId(result.getOrdersNo());
                payment.setAmount(refundAmount.intValue()+"");
                PayService payService = AbstractPayServiceImpl.getPayService(payment.getPayType(), payment.getPayModel());
                rs=payService.refund(payment);
                if(rs!=null&&rs.getCode()==RestResp.ERROR){
                    Assert.isTrue(false,"退款失败");
                }
            }

        }
        if(result.getPayWay()==5){
            //退支付宝部分
            if( refundAmount!=null){
                payment.setPayType(PayTypeDict.PAY_TYPE_ALIPAY.getCn());
                payment.setPayModel(PayModeDict.PAY_MODE_MINI_NATIVE.getCn());
                payment.setCheckoutId(result.getPaymentId());
                payment.setOrderId(result.getOrdersNo());
                payment.setAmount(refundAmount.intValue()+"");
                PayService payService = AbstractPayServiceImpl.getPayService(payment.getPayType(), payment.getPayModel());
                rs=payService.refund(payment);
                if(rs!=null&&rs.getCode()==RestResp.ERROR){
                    Assert.isTrue(false,"退款失败");
                }
            }
        }
        //加商品库存
        skuNumIncreaseOrDecrease(result.getOrdersNo(),0);
    }

    /**
     * 订单退款
     * @param ordersVo
     * @return
     */
    @Override
    public Integer reviewOrderRefunds(OrdersVo ordersVo){
        Assert.isTrue(ordersVo.getOrdersNo()!=null, "订单号不能为空");
        Orders orders=new Orders();
        orders.setOrdersNo(ordersVo.getOrdersNo());
        Orders result=ordersMapper.selectOne(orders);
        Assert.notNull(result,"找不到该订单");
        Assert.isTrue(result.getOrdersState()==OrderStatusDict.ORDER_STATUS_REFUND.getCn(), "该订单没有申请退款");
        Assert.isTrue(result.getRefundAmount()!=null || result.getRefundIntegral() !=null, "该订单退款金额为空");
        Assert.isTrue(result.getTradeState()==1, "该订单未支付不能退款");
        refundPrice(result);
        return 1;
    }

    /**
     * 退款回调处理,更新订单状态
     * @param ordersNo
     */
    @Override
    public void refundBackOrderExePre(String ordersNo){
        Assert.isTrue(ordersNo!=null, "订单号不能为空");
        logger.info("退款回调处理"+ordersNo);
        Orders orders=new Orders();
        orders.setOrdersNo(ordersNo);
        Orders result=ordersMapper.selectOne(orders);
        Assert.notNull(result,"找不到该订单");
        result.setOrdersState(OrderStatusDict.ORDER_STATUS_REFUNDED.getCn());
        Date now=new Date();
        result.setUpdateTime(now);
        ordersMapper.updateById(result);
        //拆分订单一律置为已退款
        if(result.getFatherOrders()==1||result.getFatherOrders()==0){
            if(result.getFatherOrders()==0){
                //找到父订单一并处理为已付款
                Orders ordersFather=new Orders();
                ordersFather.setOrdersNo(result.getFatherOrdersNo());
                Orders ordersFatherInfo=ordersMapper.selectOne(ordersFather);
                if(ordersFatherInfo!=null) {
                    ordersFatherInfo.setOrdersState(OrderStatusDict.ORDER_STATUS_REFUNDED.getCn());
                    ordersFatherInfo.setUpdateTime(now);
                    ordersMapper.updateById(ordersFatherInfo);
                    //减去订单商品购买数量
                    List<OrderDetail> orderDetailByOrderId = orderDetailMapper.getOrderDetailByOrderId(ordersFatherInfo.getOrdersId());
                    if(CollectionUtil.isNotEmpty(orderDetailByOrderId)){
                        for (OrderDetail orderDetail : orderDetailByOrderId) {
                            Long goodsSpuId = orderDetail.getGoodsSpuId();
                            Integer skuNum = orderDetail.getQuantity();
                            //减去购买数量
                            addPaySpuNum( ordersFatherInfo.getUserId(),  goodsSpuId,  skuNum == null?-1:skuNum * -1);
                        }
                    }
                }

            }else{
                //找到子订单一并处理为已付款
                Orders ordersFather=new Orders();
                ordersFather.setFatherOrdersNo(result.getOrdersNo());
                Orders ordersFatherInfo=ordersMapper.selectOne(ordersFather);
                if(ordersFatherInfo!=null) {
                    ordersFatherInfo.setOrdersState(OrderStatusDict.ORDER_STATUS_REFUNDED.getCn());
                    ordersFatherInfo.setUpdateTime(now);
                    ordersMapper.updateById(ordersFatherInfo);
                    //减去订单商品购买数量
                    List<OrderDetail> orderDetailByOrderId = orderDetailMapper.getOrderDetailByOrderId(ordersFatherInfo.getOrdersId());
                    if(CollectionUtil.isNotEmpty(orderDetailByOrderId)){
                        for (OrderDetail orderDetail : orderDetailByOrderId) {
                            Long goodsSpuId = orderDetail.getGoodsSpuId();
                            Integer skuNum = orderDetail.getQuantity();
                            //减去购买数量
                            addPaySpuNum( ordersFatherInfo.getUserId(),  goodsSpuId,  skuNum == null?-1:skuNum * -1);
                        }
                    }
                }
            }
        }
    }

    /**
     * 退还收益
     * @param ordersNo
     * @param userId
     * @param finalAmount
     */
    private void refundUseBenefitl(String ordersNo,Long userId,BigDecimal finalAmount){
        if (StringUtils.isBlank(ordersNo) || finalAmount==null){
            Assert.isTrue(false,"订单号和订单金额不能为空");
        }
        Orders orders = new Orders();
        orders.setOrdersNo(ordersNo);
        orders = ordersMapper.selectOne(orders);
        Assert.notNull(orders,"参数错误,无此订单");
        Date now=new Date();
        //退回收益
        TUserAccount userAccount=userAccountService.initUserAccountByUserId(userId);
        BigDecimal benefit = userAccount.getBenefit();
        BigDecimal benefitNew = DecimalUtil.addArray(finalAmount, benefit);
        userAccount.setBenefit(benefitNew);
        tUserAccountMapper.updateById(userAccount);
        BenefitTransaction bt = new BenefitTransaction( userId,userId,Long.valueOf(orders.getOrdersId()),benefitNew,
                BenefitTranTypeDict.BENEFIT_TRAN_TYPE_900.getCn(), finalAmount, "购买普通商品退回");
        userAccountService.addBenefitTransaction(bt);
    }

    /**
     * 退还积分
     * @param ordersNo
     * @param userId
     * @param useIntegral
     */
    private void refundUseIntegral(String ordersNo,Long userId,BigDecimal useIntegral){
        if (StringUtils.isBlank(ordersNo)||useIntegral==null){
            Assert.isTrue(false,"订单号和使用积分不能为空");
        }
        Date now=new Date();
        TUserAccount userAccount=userAccountService.initUserAccountByUserId(userId);
        Assert.notNull(userAccount,"找不到该用户积分信息");
        BigDecimal integral=userAccount.getIntegral().add(useIntegral);
        Orders orders = new Orders();
        orders.setOrdersNo(ordersNo);
        orders = ordersMapper.selectOne(orders);
        Assert.notNull(orders,"参数错误,无此订单");
        //退还账户积分
        userAccountService.updateUserAccount(userId,integral);
        //拆分子订单不在记积分明细,维护积分记录，在支付完扣除账户积分
        IntegralTransaction integralTransaction = new IntegralTransaction();
        integralTransaction.setUserId(userId);
        integralTransaction.setType(IntegralTranTypeDict.NTEGRAL_TRAN_TYPE_GOODS_300.getCn());
        integralTransaction.setIntegral(useIntegral);
        integralTransaction.setOrderId(Long.parseLong(orders.getOrdersId()+""));
        integralTransaction.setDes("购买商品退款退还积分");
        integralTransaction.setCreateTime(now);
        integralTransaction.setUpdateTime(now);
        if(integral!=null) {
            integralTransaction.setAccountTotalIntegral(integral);
        }
        userAccountService.addIntegralTransaction(integralTransaction);
    }
    /**
     * 获取用户购买商品实付金额,去掉已退款金额
     * @return
     */
    @Override
    public BigDecimal getTotalUserOrderFinalAmount(){
        Long currUid = SessionUtil.getCurrUid();
        return ordersMapper.getTotalUserOrderFinalAmount(currUid);
    }

    /**
     * 统计用户已付款实付金额
     * @return
     */
    public BigDecimal getFinalAmountByOrderNo(String orderNo){
        Orders orders=new Orders();
        orders.setOrdersNo(orderNo);
        Orders ordersInfo=ordersMapper.selectOne(orders);
        Assert.notNull(ordersInfo,"找不到该订单");
        return ordersInfo.getFinalAmount();
    }

    /**
    * 统计用户已退款金额
    * @return
     */
    @Override
    public BigDecimal getRefundAmountByOrderNo(String orderNo){
        Orders orders=new Orders();
        orders.setOrdersNo(orderNo);
        Orders ordersInfo=ordersMapper.selectOne(orders);
        Assert.notNull(ordersInfo,"找不到该订单");
        return ordersInfo.getRefundAmount();
    }

    @Override
    public SysConfVo getSysOrderConf(){
        SysConf sysConf=new SysConf();
        sysConf.setConfType(1);//1订单交易设置
        SysConf sysConfs=sysConfMapper.selectOne(sysConf);
        SysConfVo sys = new SysConfVo();
        BeanUtil.copyProperties(sysConfs,sys);
        //分销购买限制/成功普通会员购买限制
        SysConfig config = new SysConfig();
        config.setConfigKey(Constant.CONFIG_KEY_FENXIAO_LIMIT);
        SysConfig sysConfig = sysConfigMapper.selectOne(config);
        sys.setBuyLimit(sysConfig.getConfigValue());
        //提现比率
        String configValue = getConfigValue(Constant.CONFIG_KEY_CASH_OUT_RATE);
        sys.setCashOutRate(configValue);
        //提现规则
        configValue = getConfigValue(Constant.CONFIG_KEY_CASH_OUT_PROCOTOL);
        sys.setWithdrawalRules(configValue);
        //库存限制
        configValue = getConfigValue(Constant.CONFIG_KEY_KU_CUN_TI_XING);
        sys.setKuCunLimit(configValue);
        //大额提现限制
        configValue = getConfigValue(Constant.CONFIG_KEY_TI_XIAN_LIMIT);
        sys.setCashOutLimit(configValue);
        //商品奖励配置
        configValue = getConfigValue(Constant.CONFIG_KEY_GOOS_REWORD_RATE);
        sys.setGoodsRewordRate(configValue);
        //商品二次奖励配置
        configValue = getConfigValue(Constant.CONFIG_KEY_GOOS_REWORD_RATE_OTHER);
        sys.setGoodsRewordRateOther(configValue);
        //商品折扣比例配置
        configValue = getConfigValue(Constant.CONFIG_KEY_GOOS_DISCOUNT_RATE);
        sys.setGoodsDiscountRate(configValue);
        //商品折扣比例配置
        configValue = getConfigValue(Constant.CONFIG_KEY_DISTRIBUTION_UPGRADE_LIMIT);
        sys.setDistributionUpgradeLimt(configValue);
        //商积分返现配置
        configValue = getConfigValue(Constant.CONFIG_KEY_JI_FEN_LIMIT);
        JiFenReturnConfig jiFenReturnConfig = new JiFenReturnConfig();
        if(StringUtil.isNotEmpty(configValue)){
            JSONObject jsonObject = JSON.parseObject(configValue);
            jiFenReturnConfig.setPayIntegralLimit(jsonObject.getBigDecimal("payIntegralLimit"));
            jiFenReturnConfig.setReturnIntegral(jsonObject.getBigDecimal("returnIntegral"));
            jiFenReturnConfig.setReturnMoney(jsonObject.getBigDecimal("returnMoney"));
        }
        sys.setJiFenReturnConfig(jiFenReturnConfig);
        //商品折扣比例配置
        List<SmallPayModeVo> payModeList = new ArrayList<>();
        configValue = getConfigValue(Constant.CONFIG_KEY_PAY_MODES);
        if(StringUtils.isNotBlank(configValue)){
            SmallPayModeDict[] values = SmallPayModeDict.values();
            for (int i = 0; i < values.length; i++) {
                SmallPayModeDict value = values[i];
                SmallPayModeVo vo = new SmallPayModeVo();
                vo.setPayModeInt(value.getCn());
                vo.setPayModeName(value.getDesc());
                vo.setPayModeSelected(configValue.contains(value.getCn()+"")?1:0);
                payModeList.add(vo);
            }
        }
        sys.setPayModeList(payModeList);
        return sys;
    }


    /**
     * config 的更新或者插入
     * @param key
     * @param value 新值
     * @return
     */
    private void saveOrUpdateConfig(String value,String key){
        SysConfig config = new SysConfig();
        config.setConfigKey(key);
        SysConfig sysConfig = sysConfigMapper.selectOne(config);
        if(sysConfig == null){
            value = StringUtils.isBlank(value)?"0":value;
            sysConfig = new SysConfig();
            sysConfig.setConfigKey(key);
            sysConfig.setConfigValue(value);
            sysConfigMapper.insert(sysConfig);
        }else{
            if(StringUtils.isNotBlank(value)){
                String configValue = sysConfig.getConfigValue();
                if(!value.equals(configValue)){
                    sysConfig.setConfigValue(value);
                    sysConfigMapper.updateById(sysConfig);
                }
            }

        }
    }

    /**
     * config 根据key获取config
     * @param key
     * @return
     */
    private String getConfigValue(String key){
        SysConfig config = new SysConfig();
        config.setConfigKey(key);
        config = sysConfigMapper.selectOne(config);
        String value = null;
        if(config!=null){
            value = config.getConfigValue();
        }
        return value;
    }
    /**
     * 添加系统配置
     * @param sysConf
     * @return
     */
    @Override
    public Integer createOrUpdateSysOrderConf(SysConfVo sysConf){
        Assert.notNull(sysConf,"参数为空");
        Assert.isTrue(sysConf.getOrderAutoArrival()!=null&&sysConf.getOrderAutoArrival()!=0,"不能为空并必须大于0");
        Assert.isTrue(sysConf.getOrderCancelTime()!=null&&sysConf.getOrderCancelTime()!=0,"不能为空并必须大于0");
        //针对普通会员购买限制的修改
        saveOrUpdateConfig(sysConf.getBuyLimit(),Constant.CONFIG_KEY_FENXIAO_LIMIT);
        //更新提现费率
        Assert.isTrue(new BigDecimal(sysConf.getCashOutRate()).compareTo(new BigDecimal("100"))<=0,"费率不得超过1");
        saveOrUpdateConfig(sysConf.getCashOutRate(),Constant.CONFIG_KEY_CASH_OUT_RATE);
        //更新提现限制
        saveOrUpdateConfig(sysConf.getCashOutLimit(),Constant.CONFIG_KEY_TI_XIAN_LIMIT);
        //更新分销协议
        saveOrUpdateConfig(sysConf.getWithdrawalRules(),Constant.CONFIG_KEY_CASH_OUT_PROCOTOL);
        //更新商品收益比率规则
        saveOrUpdateConfig(sysConf.getGoodsRewordRate(),Constant.CONFIG_KEY_GOOS_REWORD_RATE);
        //更新商品收益比率规则 二次以及以后
        saveOrUpdateConfig(sysConf.getGoodsRewordRateOther(),Constant.CONFIG_KEY_GOOS_REWORD_RATE_OTHER);
        //更新商品折扣比率规则
        saveOrUpdateConfig(sysConf.getGoodsDiscountRate(),Constant.CONFIG_KEY_GOOS_DISCOUNT_RATE);
        //更新小程序支付方式规则
        saveOrUpdateConfig(sysConf.getPayModes(),Constant.CONFIG_KEY_PAY_MODES);
        //更新分销人数升级插队规则
        saveOrUpdateConfig(sysConf.getDistributionUpgradeLimt(),Constant.CONFIG_KEY_DISTRIBUTION_UPGRADE_LIMIT);
        //更新库存限制
        saveOrUpdateConfig(sysConf.getKuCunLimit(),Constant.CONFIG_KEY_KU_CUN_TI_XING);
        //更新积分 返现配置
        JiFenReturnConfig jiFenReturnConfig = sysConf.getJiFenReturnConfig();
        if(jiFenReturnConfig!=null){
            String jiFenReturnConfigStr = JSON.toJSONString(jiFenReturnConfig);
            saveOrUpdateConfig(jiFenReturnConfigStr,Constant.CONFIG_KEY_JI_FEN_LIMIT);
        }
        Date now=new Date();
        if(sysConf.getConfId()!=null){
            SysConf sysConf1=sysConfMapper.selectById(sysConf.getConfId());
            sysConf1.setOrderAutoArrival(sysConf.getOrderAutoArrival());
            sysConf1.setOrderCancelTime(sysConf.getOrderCancelTime());
            sysConf1.setReturnAddress(sysConf.getReturnAddress());
            sysConf1.setUpdateTime(now);
            return sysConfMapper.updateById(sysConf1);
        }else{
            SysConf conf = new SysConf();
            BeanUtil.copyProperties(sysConf,conf);
            sysConf.setCreateTime(now);
            sysConf.setUpdateTime(now);
            return sysConfMapper.insertAllColumn(conf);
        }
    }

    /**
     * 获取物流快递公司
     * @return
     */
    @Override
    public List<Logistics> getLogisticsInfo(){
        List<Logistics> logisticsList=logisticsMapper.selectList(null);
        return logisticsList;
    }

    /**
     * 获取订单物流信息
     * @param ordersLogistics
     * @return
     */
    @Override
    public List<OrdersLogistics> getOrdersLogisticsList(OrdersLogistics ordersLogistics){
        Map<String,Object> paramMap=new HashMap<>();
        paramMap.put("orders_no",ordersLogistics.getOrdersNo());
        if(ordersLogistics.getType()!=null){
            paramMap.put("type",ordersLogistics.getType());
        }
        List<OrdersLogistics> logisticsList=ordersLogisticsMapper.selectByMap(paramMap);
        return logisticsList;
    }

    /**
     * 添加订单快递信息(发货换货)
     * @param ordersLogistics
     * @return
     */
    @Override
    public Integer createOrUpdateOrdersLogistics(OrdersLogistics ordersLogistics){
        Date now=new Date();
        if(ordersLogistics.getId()!=null){
            ordersLogistics.setUpdateTime(now);
            return ordersLogisticsMapper.updateAllColumnById(ordersLogistics);
        }else{
            Assert.notNull(ordersLogistics,"参数不能为空");
            if(ordersLogistics.getType()!=null&ordersLogistics.getType()==1){
                //订单置为已发货
                Orders orders=new Orders();
                orders.setOrdersNo(ordersLogistics.getOrdersNo());
                Orders ordersInfo=ordersMapper.selectOne(orders);
                Assert.notNull(ordersInfo,"找不到该订单");
                ordersInfo.setOrdersState(OrderStatusDict.ORDER_STATUS_DELIVERY.getCn());
                ordersInfo.setUpdateTime(now);
                ordersMapper.updateById(ordersInfo);
                Message message=new Message();
                message.setUserId(ordersInfo.getUserId());
                message.setOrderId(Long.parseLong(ordersInfo.getOrdersId().toString()));
                message.setOrderType(1);
                message.setType(0);
                message.setMessage("商品订单:"+ordersInfo.getOrdersNo()+"已发货");
                userAccountService.addUserMessage(message);
            }
            ordersLogistics.setCreateTime(now);
            ordersLogistics.setUpdateTime(now);
            return ordersLogisticsMapper.insertAllColumn(ordersLogistics);
        }
    }

    /**
     * 系统按设定的时间取消
     */
    @Override
    public void cancelOrder(){
        SysConf sysConf=new SysConf();
        sysConf.setConfType(1);
        SysConf sysConfData=sysConfMapper.selectOne(sysConf);
        if(sysConfData!=null&&sysConfData.getOrderCancelTime()!=null) {
            List<Orders> ordersList=ordersMapper.cancelOrderList(sysConfData.getOrderCancelTime());
            if(!CollectionUtils.isEmpty(ordersList)){
                for (Orders o:ordersList){
                    if(o.getUseIntegral()!=null){
                        Integer tradeState = o.getTradeState();
                        if(tradeState!=null && tradeState == 1){
                            //有积分退还积分
                            refundUseIntegral(o.getOrdersNo(),o.getUserId(),o.getUseIntegral());
                        }
                    }
                }
            }
            ordersMapper.cancelOrder(sysConfData.getOrderCancelTime());
        }else{
            Assert.isTrue(false, "找不到交易设置");
        }
    }

    /**
     * 取消订单
     * @param ordersNo
     * @return
     */
    @Override
    public Integer cancelOrder(String ordersNo){
        Orders orders=new Orders();
        orders.setOrdersNo(ordersNo);
        Orders data=ordersMapper.selectOne(orders);
        Assert.notNull(data,"找不到该订单");
        data.setOrdersState(OrderStatusDict.ORDER_STATUS_CLOSED.getCn());
        data.setUpdateTime(new Date());
        //有积分退还积分
        if(data.getUseIntegral()!=null){
            Integer tradeState = data.getTradeState();
            if(tradeState!=null && tradeState == 1){
                refundUseIntegral(ordersNo,data.getUserId(),data.getUseIntegral());
                Integer payWay = data.getPayWay();
                if(payWay == 10){
                    //如果收益支付,退回收益
                    refundUseBenefitl(ordersNo,data.getUserId(),data.getFinalAmount());
                }
            }
        }
        //减去订单数量
        List<OrderDetail> orderDetailByOrderId = orderDetailMapper.getOrderDetailByOrderId(data.getOrdersId());
        if(CollectionUtil.isNotEmpty(orderDetailByOrderId)){
            for (OrderDetail orderDetail : orderDetailByOrderId) {
                Long goodsSpuId = orderDetail.getGoodsSpuId();
                Integer skuNum = orderDetail.getQuantity();
                //减去购买数量
                addPaySpuNum( data.getUserId(),  goodsSpuId,  skuNum == null?-1:skuNum * -1);
            }
        }
        return ordersMapper.updateById(data);
    }

    /**
     * 系统自动确认收货
     */
    @Override
    public void confirmOrderArrival(){
        SysConf sysConf=new SysConf();
        sysConf.setConfType(1);
        SysConf sysConfData=sysConfMapper.selectOne(sysConf);
        if(sysConfData!=null) {
            //获取所有的需要自动确认收货的订单
            List<Orders> autoConfirmOrder = ordersMapper.getAutoConfirmOrder(sysConfData.getOrderAutoArrival());
            if (CollectionUtils.isEmpty(autoConfirmOrder)){
                for (Orders orders : autoConfirmOrder) {
                    try{
                        userConfirmOrderArrival(orders.getUserId(),orders.getOrdersNo());
                    }catch (Exception e){
                        log.error("confirmOrderArrival orderId:{}",orders.getOrdersId(),e);
                    }
                }
            }
        }else{
            Assert.isTrue(false, "找不到交易设置");
        }
    }

    /**
     * 商品佣金处理方法
     */
    private void orderGoodsReward(Long userId,Orders ordersInfo){
        //确认收货时,进行推荐人收益处理
        User user = userMapper.getById(userId);
        Long shareUserId = user.getShareUserId();
        Integer level = user.getLevel();

        if(shareUserId!=null &&userId.equals(shareUserId) && (level == null || level==0)){
            //如果推荐人是自己,但是自己不是会员的时候,则不享受收益
            return;
        }
        User shareUser = userMapper.getById(user.getShareUserId());
        Integer payWay = ordersInfo.getPayWay();
        if(shareUser != null && payWay!=null && (payWay == 1 || payWay == 3|| payWay == 10)){
            TUserAccount tUserAccount = userAccountService.initUserAccountByUserId(user.getShareUserId());
            BigDecimal benefit = tUserAccount.getBenefit();
            //获取商品原总金额和当时的收益比率
            Integer shareGoodsRewardsHave = user.getShareGoodsRewardsHave();
            String configValue = null;
            if(shareGoodsRewardsHave == null || 0 == shareGoodsRewardsHave){
                //保存当时的商品商品收益比率
                configValue = getConfigValue(Constant.CONFIG_KEY_GOOS_REWORD_RATE);
                user.setShareGoodsRewardsHave(1);
                userMapper.update(user);
            }else{
                //二次奖励
                configValue = getConfigValue(Constant.CONFIG_KEY_GOOS_REWORD_RATE_OTHER);
            }
            BigDecimal rewordRate = new BigDecimal(configValue).divide(new BigDecimal(100));
            ordersInfo.setRewordRate(rewordRate);
            BigDecimal originalAmount = ordersInfo.getOriginalAmount();
            BigDecimal rewordAmount = originalAmount.multiply(rewordRate);
            benefit = DecimalUtil.addArray(benefit,rewordAmount);
            tUserAccount.setBenefit(benefit);
            tUserAccountMapper.updateById(tUserAccount);
            //添加受益流水
            BenefitTransaction bt = new BenefitTransaction();
            bt.setCreateTime(new Date());
            bt.setType(BenefitTranTypeDict.BENEFIT_TRAN_TYPE_400.getCn());
            bt.setDes(shareGoodsRewardsHave == null || 0 == shareGoodsRewardsHave?"首次购买了商品":"购买了商品");
            bt.setOrderId(Long.valueOf(ordersInfo.getOrdersId()));
            bt.setCurrentTotalBenefit(benefit);
            bt.setBenefit(rewordAmount);
            bt.setUserId(user.getShareUserId());
            //获取此类型当前收益总额
            List<Integer> typeList = new ArrayList<>();
            typeList.add(bt.getType());
            BigDecimal sumType = benefitTransactionMapper.getSumByTypeList(bt.getUserId(),typeList);
            bt.setCurrentTypeBenefit(DecimalUtil.addArray(bt.getBenefit(),sumType));
            benefitTransactionMapper.insert(bt);
        }
    }

    /**
     * 用户确认收货
     * @param userId
     * @param orderNo
     * @return
     */
    @Override
    public Integer userConfirmOrderArrival(Long userId,String orderNo){
        Orders orders=new Orders();
        orders.setOrdersNo(orderNo);
        orders.setUserId(userId);
        Orders ordersInfo=ordersMapper.selectOne(orders);
        Assert.notNull(ordersInfo,"找不到该订单");
        Assert.isTrue(OrderStatusDict.ORDER_STATUS_DELIVERY.getCn()==ordersInfo.getOrdersState(),"订单未发货不能确认收货");
        //如果是非会员订单,则进行受益处理
        Integer vipOrder = ordersInfo.getVipOrder();
        if(vipOrder == null || vipOrder ==0){
            orderGoodsReward(userId,ordersInfo);
        }
        //积分返现处理
        BigDecimal useIntegral = ordersInfo.getUseIntegral();
        if(useIntegral!=null && useIntegral.compareTo(BigDecimal.ZERO)>0){
            //如果使用了积分,则判断是否需要积分返现
            String configValue = getConfigValue(Constant.CONFIG_KEY_JI_FEN_LIMIT);
            userAccountService.integralReturn(useIntegral,userId,configValue);
        }
        ordersInfo.setOrdersState(OrderStatusDict.ORDER_STATUS_SUCCESS.getCn());
        ordersInfo.setUpdateTime(new Date());
        return ordersMapper.updateById(ordersInfo);
    }

    /**
     * 支付成功商品订单相关回调处理
     * @param payType
     * @param orderId
     * @param orderType
     */
    @Override
    public void payOrderProcess(Integer payType, String orderId, Integer orderType){
        log.debug("支付成功商品订单相关回调处理payOrderProcess:"+orderId);
        Orders orders=new Orders();
        orders.setOrdersNo(orderId);
        Orders ordersInfo=ordersMapper.selectOne(orders);
        Assert.notNull(ordersInfo,"找不到该订单");
        //amount校验支付金额是否跟订单金额不符
        BigDecimal orderUseIntegral=ordersInfo.getUseIntegral();
        Long userId=ordersInfo.getUserId();
        User byId = userMapper.getById(userId);
        ordersInfo.setTradeState(1);//交易完成
        Integer vipOrder = ordersInfo.getVipOrder();
        if(vipOrder!=null && vipOrder == 1){
            ordersInfo.setOrdersState(OrderStatusDict.ORDER_STATUS_SUCCESS.getCn());
        }else{
            ordersInfo.setOrdersState(OrderStatusDict.ORDER_STATUS_PAIED.getCn());
        }
        Date now=new Date();
        ordersInfo.setUpdateTime(now);
        ordersMapper.updateById(ordersInfo);
        if(ordersInfo.getFatherOrders()==1||ordersInfo.getFatherOrders()==0){
            if(ordersInfo.getFatherOrders()==0){
                //找到父订单一并处理为已付款
                Orders ordersFather=new Orders();
                ordersFather.setOrdersNo(ordersInfo.getFatherOrdersNo());
                Orders ordersFatherInfo=ordersMapper.selectOne(ordersFather);
                if(ordersFatherInfo!=null) {
                    ordersFatherInfo.setTradeState(1);//交易完成
                    ordersFatherInfo.setOrdersState(OrderStatusDict.ORDER_STATUS_PAIED.getCn());
                    ordersFatherInfo.setUpdateTime(now);
                    ordersMapper.updateById(ordersFatherInfo);
                }
            }else{
                //找到子订单一并处理为已付款
                Orders ordersFather=new Orders();
                ordersFather.setFatherOrdersNo(orderId);
                Orders ordersFatherInfo=ordersMapper.selectOne(ordersFather);
                if(ordersFatherInfo!=null) {
                    ordersFatherInfo.setTradeState(1);//交易完成
                    ordersFatherInfo.setOrdersState(OrderStatusDict.ORDER_STATUS_PAIED.getCn());
                    ordersFatherInfo.setUpdateTime(now);
                    ordersMapper.updateById(ordersFatherInfo);
                }
            }
            Message message=new Message();
            message.setUserId(-1L);
            message.setOrderId((long)ordersInfo.getOrdersId());
            message.setOrderType(1);
            message.setType(3);
            message.setMessage(byId.getUsername()+"购买了商品订单,订单编号:"+ordersInfo.getOrdersNo());
            userAccountService.addUserMessage(message);
        }
        log.debug("END支付成功商品订单相关回调处理payOrderProcess:"+orderId);
        if(orderUseIntegral!=null) {
            TUserAccount tUserAccount = userAccountService.initUserAccountByUserId(userId);
            useIntegralCommon( userId, ordersInfo.getOrdersId(),tUserAccount,orderUseIntegral);
            tUserAccountMapper.updateById(tUserAccount);
        }
        BigDecimal finalAmount = ordersInfo.getFinalAmount();
        //没有积分支付,满足条件给会员升级
        if(finalAmount!=null){
            BigDecimal totalUserOrderFinalAmount=ordersMapper.getTotalUserOrderFinalAmount(userId);
            User user=userMapper.getUserById(userId);
            if(user!=null) {
                //并且该用户是0，升级为1
                SysConfig config1 = new SysConfig();
                config1.setConfigKey(Constant.CONFIG_KEY_FENXIAO_LIMIT);
                SysConfig sysConfig = sysConfigMapper.selectOne(config1);
                String buyLimit = sysConfig.getConfigValue();
                buyLimit = StringUtils.isBlank(buyLimit)?"0":buyLimit;
                totalUserOrderFinalAmount = totalUserOrderFinalAmount == null?BigDecimal.ZERO:totalUserOrderFinalAmount;
                if (UserLevelDict.USER_LEVEL_0.getCn() ==user.getLevel()  && totalUserOrderFinalAmount.compareTo(new BigDecimal(buyLimit)) >= 0) {
                    user.setLevel(UserLevelDict.USER_LEVEL_1.getCn());
                    userMapper.update(user);
                }
            }
            //如果是会员商品,则支付成功给推荐人添加收益
            if(vipOrder!=null && vipOrder == 1){
                orderGoodsReward(userId,ordersInfo);
                BigDecimal integralUpdate = DecimalUtil.mulArray(finalAmount, new BigDecimal("10"));
                //会员商品支付成功,则曾松等额积分
                TUserAccount acc = userAccountService.initUserAccountByUserId(userId);
                BigDecimal integral = acc.getIntegral();
                integral = DecimalUtil.addArray(integralUpdate,integral);
                acc.setIntegral(integral);
                tUserAccountMapper.updateById(acc);
                //添加积分流水记录
                IntegralTransaction it = new IntegralTransaction();
                it.setCreateTime(new Date());
                it.setType(IntegralTranTypeDict.NTEGRAL_TRAN_TYPE_GOODS.getCn());
                it.setOrderId(Long.valueOf(ordersInfo.getOrdersId().toString()));
                it.setDes("购买会员商品积分增加");
                it.setIntegral(integralUpdate);
                it.setUserId(ordersInfo.getUserId());
                //变更后积分
                it.setAccountTotalIntegral(integral);
                userAccountService.addIntegralTransaction(it);
            }
        }
        //减去订单商品销量
        skuNumIncreaseOrDecrease(orderId,1);
    }


    /**
     * 支付时商品订单相关前置处理
     * @param orderId
     * @param checkoutId
     */
    @Override
    public void payOrderProcess(String orderId,Long checkoutId){
        log.debug("支付时商品订单相关前置处理,检查实付金额和订单金额是否相等,订单支付时间支付ID");
        Orders orders=new Orders();
        orders.setOrdersNo(orderId);
        Orders ordersInfo=ordersMapper.selectOne(orders);
        Assert.notNull(ordersInfo,"找不到该订单");
        Date now=new Date();
        ordersInfo.setPaymentId(checkoutId);
        ordersInfo.setPayTime(now);
        ordersInfo.setUpdateTime(now);
        ordersMapper.updateById(ordersInfo);
        if(ordersInfo.getFatherOrders()==1||ordersInfo.getFatherOrders()==0){
            if(ordersInfo.getFatherOrders()==0){
                //找到父订单一并处理为已付款
                Orders ordersFather=new Orders();
                ordersFather.setOrdersNo(ordersInfo.getFatherOrdersNo());
                Orders ordersFatherInfo=ordersMapper.selectOne(ordersFather);
                if(ordersFatherInfo!=null) {
                    ordersFatherInfo.setPaymentId(checkoutId);
                    ordersFatherInfo.setUpdateTime(now);
                    ordersMapper.updateById(ordersFatherInfo);
                }
            }else{
                //找到子订单一并处理为已付款
                Orders ordersFather=new Orders();
                ordersFather.setFatherOrdersNo(orderId);
                Orders ordersFatherInfo=ordersMapper.selectOne(ordersFather);
                if(ordersFatherInfo!=null) {
                    ordersFatherInfo.setPaymentId(checkoutId);
                    ordersFatherInfo.setUpdateTime(now);
                    ordersMapper.updateById(ordersFatherInfo);
                }
            }
        }
    }

    /**
     * 用户申请订单退货
     * @return
     */
    @Override
    public Integer returnReview(OrdersLogistics ordersLogistics){
        Assert.notNull(ordersLogistics,"参数不能为空");
        Assert.isTrue(ordersLogistics.getOrdersNo()!=null,"订单号不能为空");
        Assert.isTrue(ordersLogistics.getLogisticsName()!=null,"快递公司不能为空");
        Assert.isTrue(ordersLogistics.getDeliveryOrdersNo()!=null,"快递单号不能为空");
        Assert.isTrue(ordersLogistics.getReturnAddress()!=null,"退换货地址不能为空");
        Assert.isTrue(ordersLogistics.getReturnDes()!=null,"退货原因不能为空");
        Date now=new Date();
        ordersLogistics.setType(2);
        ordersLogistics.setCreateTime(now);
        ordersLogistics.setUpdateTime(now);
        Orders ordersFather=new Orders();
        ordersFather.setOrdersNo(ordersLogistics.getOrdersNo());
        Orders ordersFatherInfo=ordersMapper.selectOne(ordersFather);
        Integer result=null;
        if(ordersFatherInfo!=null) {
            Integer vipOrder = ordersFatherInfo.getVipOrder();
            Assert.isTrue(vipOrder == null || vipOrder == 0,"会员商品不支持退货");
            Assert.isTrue(ordersFatherInfo.getReturnTime()==null,"该订单已经申请了退货");
            ordersFatherInfo.setOrdersState(OrderStatusDict.ORDER_STATUS_RETURN.getCn());
            ordersFatherInfo.setReturnDes(ordersLogistics.getReturnDes());
            if(ordersLogistics.getReturnImg()!=null) {
                ordersFatherInfo.setReturnImg(ordersLogistics.getReturnImg());
            }
            ordersFatherInfo.setReturnTime(now);
            ordersFatherInfo.setUpdateTime(now);
            result=ordersMapper.updateById(ordersFatherInfo);
        }
        ordersLogisticsMapper.insertAllColumn(ordersLogistics);
        return result;
    }

    /**
     * 订单退货审核
     * @return
     */
    @Override
    public Integer reviewOrderReturn(OrdersLogistics ordersLogistics){
        Orders ordersFather=new Orders();
        ordersFather.setOrdersNo(ordersLogistics.getOrdersNo());
        Orders ordersFatherInfo=ordersMapper.selectOne(ordersFather);
        Integer result=null;
        if(ordersFatherInfo!=null) {
            //退款处理
            ordersFatherInfo.setRefundAmount(ordersFatherInfo.getFinalAmount());
            ordersFatherInfo.setRefundIntegral(ordersFatherInfo.getUseIntegral());
            Integer vipOrder = ordersFatherInfo.getVipOrder();
            Assert.isTrue(vipOrder ==null || vipOrder == 0,"会员商品不支持退货");
            if(vipOrder !=null && vipOrder == 1){
                //加商品库存
                skuNumIncreaseOrDecrease(ordersFatherInfo.getOrdersNo(),0);
            }else{
                refundPrice(ordersFatherInfo);
            }
            ordersFatherInfo.setOrdersState(OrderStatusDict.ORDER_STATUS_RETURNED.getCn());
            //减去订单数量
            //减去订单商品购买数量
            List<OrderDetail> orderDetailByOrderId = orderDetailMapper.getOrderDetailByOrderId(ordersFatherInfo.getOrdersId());
            if(CollectionUtil.isNotEmpty(orderDetailByOrderId)){
                for (OrderDetail orderDetail : orderDetailByOrderId) {
                    Long goodsSpuId = orderDetail.getGoodsSpuId();
                    Integer skuNum = orderDetail.getQuantity();
                    //减去购买数量
                    addPaySpuNum( ordersFatherInfo.getUserId(),  goodsSpuId,  skuNum == null?-1:skuNum * -1);
                }
            }
            ordersFatherInfo.setUpdateTime(new Date());
            result=ordersMapper.updateById(ordersFatherInfo);
        }
        return result;
    }


    /**
     * 撤销申请
     * @param ordersNo
     * @param type
     * @return
     */
    @Override
    public Integer revokeApply(String ordersNo,Integer type){
        Assert.isTrue(ordersNo!=null,"订单号不能为空");
        Assert.isTrue(type!=null,"类型不能为空");
        Orders orders=new Orders();
        orders.setOrdersNo(ordersNo);
        Orders data=ordersMapper.selectOne(orders);
        Assert.notNull(data,"找不到该订单");
        if(type==1){
            //1取消退款申请,重置已付款
            data.setOrdersState(OrderStatusDict.ORDER_STATUS_PAIED.getCn());
            data.setRefundTime(null);
            data.setRefundAmount(null);
            data.setRefundDes(null);
            data.setRefundImg(null);
        }else if(type==2){
            //2取消退货申请,重置已发货
            data.setOrdersState(OrderStatusDict.ORDER_STATUS_DELIVERY.getCn());
            data.setReturnTime(null);
        }
        Long currUid = SessionUtil.getCurrUid();
        User byId = userMapper.getById(currUid);
        Message message=new Message();
        message.setUserId(-1L);
        message.setOrderId((long)data.getOrdersId());
        message.setOrderType(1);
        message.setType(3);
        message.setMessage(byId.getUsername()+"取消了了商品订单退款,订单编号:"+data.getOrdersNo());
        userAccountService.addUserMessage(message);
        data.setUpdateTime(new Date());
        return ordersMapper.updateAllColumnById(data);
    }

    /**
     * 增减商品库存
     * @param ordersNo
     * @param type
     */
    private void skuNumIncreaseOrDecrease(String ordersNo,int type){
        Map<String,Object> param=new HashMap<>();
        param.put("orders_no",ordersNo);
        List<OrderDetail> orderDetailResult=orderDetailMapper.selectByMap(param);
        if(!CollectionUtils.isEmpty(orderDetailResult)) {
            if(type==1) {//减少商品库存
                for (OrderDetail od : orderDetailResult) {
                    TGoodsSku paramSku = new TGoodsSku();
                    paramSku.setId(od.getSkuId());
                    TGoodsSku resultSku = tGoodsSkuMapper.selectOne(paramSku);
                    if (resultSku != null) {
                        //减库存
                        int skuNumNew = resultSku.getSkuNum() - od.getQuantity();
                        resultSku.setSkuNum(skuNumNew);
                        //加销量
                        resultSku.setSkuSaleNum(resultSku.getSkuSaleNum() + od.getQuantity());
                        resultSku.setUpdateTime(new Date());
                        tGoodsSkuMapper.updateAllColumnById(resultSku);
                        //检查是否需要减少添加库存提醒
                        String configValue = getConfigValue(Constant.CONFIG_KEY_KU_CUN_TI_XING);
                        if(StringUtil.isNotEmpty(configValue) && Integer.valueOf(configValue)<=skuNumNew){
                            TGoodsSpu tGoodsSpu = tGoodsSpuMapper.selectById(resultSku.getGoodsSpuId());
                            Message message=new Message();
                            message.setUserId(-1L);
                            message.setOrderType(4);
                            message.setType(3);
                            message.setMessage("商品库存不足,商品名称:"+tGoodsSpu.getGoodsName()+"规格为:"+resultSku.getSkuTitle());
                            userAccountService.addUserMessage(message);
                        }
                    }
                }
            }else{
                //增加商品库存
                for (OrderDetail od : orderDetailResult) {
                    TGoodsSku paramSku = new TGoodsSku();
                    paramSku.setId(od.getSkuId());
                    TGoodsSku resultSku = tGoodsSkuMapper.selectOne(paramSku);
                    if (resultSku != null) {
                        //加库存
                        resultSku.setSkuNum(resultSku.getSkuNum()+od.getQuantity());
                        //减销量
                        resultSku.setSkuSaleNum(resultSku.getSkuSaleNum() - od.getQuantity());
                        resultSku.setUpdateTime(new Date());
                        tGoodsSkuMapper.updateAllColumnById(resultSku);
                    }
                }
            }
        }
    }

    public String payCheckSkuNum(String ordersNo){
        StringBuffer resultStr=new StringBuffer();
        Map<String,Object> param=new HashMap<>();
        param.put("orders_no",ordersNo);
        List<OrderDetail> orderDetailResult=orderDetailMapper.selectByMap(param);
        if(!CollectionUtils.isEmpty(orderDetailResult)) {
            for (OrderDetail od : orderDetailResult) {
                //判断商品库存是否充足
                String result =goodsService.checkAddSkuNum(od.getSkuId(),BigDecimal.valueOf(od.getQuantity()));
                if(StringUtils.isNotBlank(result)) {
                    resultStr.append(od.getGoodsName()).append(result).append(" ");
                }
            }
        }
        if(resultStr.length()>0
                && !"null".equals(resultStr.toString())
                &&!"".equals(resultStr.toString())) {
            return resultStr.toString();
        }else{
            return "";
        }
    }

    @Override
    public List<SmallPayModeVo> getSmallPayMode() {
        List<SmallPayModeVo> list = new ArrayList<>();
        String configValue = getConfigValue(Constant.CONFIG_KEY_PAY_MODES);
        if(StringUtils.isNotBlank(configValue)){
            String[] split = configValue.split(",");
            for (String s : split) {
                SmallPayModeDict smallPayMode = SmallPayModeDict.getSmallPayMode(Integer.valueOf(s));
                SmallPayModeVo vo = new SmallPayModeVo();
                int cn = smallPayMode.getCn();
                if(cn == SmallPayModeDict.SMALL_PAY_MODE_4.getCn()){
                    //获取平台银行卡信息
                    PlatformBankCard platformBankCard = new PlatformBankCard();
                    platformBankCard.setStop(0);
                    platformBankCard = platformBankCardMapper.selectOne(platformBankCard);
                    PlatformBankCardVo platformBankCardVo = new PlatformBankCardVo();
                    BeanUtil.copyProperties(platformBankCard,platformBankCardVo);
                    vo.setPlatformBankCardVo(platformBankCardVo);
                }
                vo.setPayPngUrl( SmallPayModeDict.getSmallPayUrl(cn));
                SmallPayModeDict.getSmallPayMode(cn);
                vo.setPayModeInt(smallPayMode.getCn());
                vo.setPayModeName(smallPayMode.getDesc());
                list.add(vo);
            }
        }
        return list;
    }


    @Override
    public void useBalancePay(String ordersNo) {
        if (StringUtils.isBlank(ordersNo)){
            Assert.isTrue(false,"订单号和使用收益金额不能为空");
        }
        Orders orders=new Orders();
        orders.setOrdersNo(ordersNo);
        Orders data=ordersMapper.selectOne(orders);
        Assert.notNull(data,"找不到该订单号");
        Long userId = data.getUserId();
        Long ordersState = data.getOrdersState();
        if(ordersState!=null && OrderStatusDict.ORDER_STATUS_CREATED.getCn() == ordersState){
            BigDecimal finalAmount = data.getFinalAmount();
            TUserAccount userAccount = userAccountService.initUserAccountByUserId(data.getUserId());
            //判断收益是足以支付
            BigDecimal benefit = userAccount.getBenefit();
            BigDecimal benefitNew = DecimalUtil.subArrayOriginalValue(benefit, finalAmount);
            Assert.isTrue(benefitNew.compareTo(BigDecimal.ZERO)>=0,"支付失败,收益金额不足");
            //进行库存判断
            String checkResult=payCheckSkuNum(ordersNo);
            Assert.isTrue(checkResult=="",checkResult);
            userAccount.setBenefit(benefitNew);
            tUserAccountMapper.updateById(userAccount);
            log.info("useBalancePay BenefitTransaction userId:{},orders:{},benefitNew:{},finalAmount:{}"
                    ,userId,data.getOrdersId(),benefitNew,finalAmount);
            BenefitTransaction bt = new BenefitTransaction( userId,userId,Long.valueOf(data.getOrdersId()),benefitNew,
                    BenefitTranTypeDict.BENEFIT_TRAN_TYPE_800.getCn(), finalAmount.negate(), "购买普通商品");
            userAccountService.addBenefitTransaction(bt);
            payOrderProcess(PaymentTypeDict.PAYMENT_TYPE_PAY.getCn(), ordersNo, OrderTypeDict.ORDER_TYPE_GOODS.getCn());
        }
    }

    @Override
    public void addPaySpuNum(Long userId, Long spuId, Integer num) {
        //添加购买数量
        UserSpuPayNum userSpuPayNum = new UserSpuPayNum();
        userSpuPayNum.setUserId(userId);
        userSpuPayNum.setSpuId(spuId);
        userSpuPayNum = userSpuPayNumMapper.selectOne(userSpuPayNum);
        if(userSpuPayNum == null){
            userSpuPayNum = new UserSpuPayNum();
            userSpuPayNum.setUserId(userId);
            userSpuPayNum.setSpuId(spuId);
            userSpuPayNum.setNum(num);
            userSpuPayNumMapper.insert(userSpuPayNum);
        }else{
            userSpuPayNum.setNum(num+userSpuPayNum.getNum());
            userSpuPayNumMapper.updateById(userSpuPayNum);
        }

    }
}
